import axios, { AxiosResponse, AxiosError } from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Token 管理
const getToken = (): string | null => {
  if (typeof window !== 'undefined') {
    return localStorage.getItem('token')
  }
  return null
}

const setToken = (token: string): void => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('token', token)
  }
}

const removeToken = (): void => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('token')
  }
}

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    return response
  },
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      removeToken()
      if (typeof window !== 'undefined') {
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

// API 接口定义
export const authAPI = {
  login: (credentials: { username: string; password: string }) =>
    api.post('/auth/login', credentials),
  logout: () => api.post('/auth/logout'),
  getProfile: () => api.get('/auth/profile'),
}

export const dashboardAPI = {
  getStats: () => api.get('/dashboard/stats'),
  getRealtime: () => api.get('/dashboard/realtime'),
}

export const deviceAPI = {
  getList: (params?: any) => api.get('/devices', { params }),
  getById: (id: string) => api.get(`/devices/${id}`),
  create: (data: any) => api.post('/devices', data),
  update: (id: string, data: any) => api.put(`/devices/${id}`, data),
  delete: (id: string) => api.delete(`/devices/${id}`),
  control: (id: string, action: string) => api.post(`/devices/${id}/control`, { action }),
  getStats: () => api.get('/devices/stats/summary'),
}

export const energyAPI = {
  getConsumption: (params?: any) => api.get('/energy/consumption', { params }),
  getStats: () => api.get('/energy/stats'),
}

export const securityAPI = {
  getAlerts: (params?: any) => api.get('/security/alerts', { params }),
  getEvents: (params?: any) => api.get('/security/events', { params }),
}

export const parkingAPI = {
  getSpaces: () => api.get('/parking/spaces'),
  getReservations: (params?: any) => api.get('/parking/reservations', { params }),
}

export { setToken, removeToken, getToken }
export default api

